package com.cloudbroker.openapi.controller;

import static com.cloudbroker.bcs.platform.dav.common.util.RequestUtil.getSingleParameterMapForBody;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudbroker.bcs.common.util.MD5Util;
import com.cloudbroker.bcs.common.util.OrderNumberUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.wechat.vo.PayCallback;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.business.FansT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.ext.annotation.SaveLog;
import com.cloudbroker.bcs.platform.dav.common.util.RequestUtil;

@Controller
public class WechatController {
    
    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);
    
    @Resource
    private FansT2BizService fansT2;
    
    @ResponseBody
    @RequestMapping("/func_pay_callback")
    @SaveLog(remark = "微信支付异步回调")
    public void payCallback(HttpServletRequest request, HttpServletResponse response, String jsonpcallback)
            throws IOException, DocumentException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map<String, Object> reqMap = RequestUtil.getSingleParameterMapForBody(request);
        TreeMap<String, Object> treeMap = new TreeMap<>();
        for (Entry<String, Object> value : reqMap.entrySet()) {
            if(!"sign".equals(value.getKey())){
                treeMap.put(value.getKey(), String.valueOf(value.getValue()));
            }
        }
        String reqsn = String.valueOf(reqMap.get("cusorderid"));
        Long brokerId = OrderNumberUtil.decode(reqsn.substring(reqsn.length() - OrderNumberUtil.LENGTH));
        treeMap.put("key", ConfigValues.getTongLianKey(brokerId));
        String sign = MD5Util.encrypt(MD5Util.dictSortTL(treeMap));
        PayCallback form = getSingleParameterMapForBody(request, PayCallback.class);
        if (sign.equals(form.getSign())) {
            fansT2.funcUserRecharge(form);
        } else {
            logger.error("---------->   非法验签        <----------");
        }
        response.getWriter().write("success");
    }
}
